package com.wanglei.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wanglei.constants.SystemConstants;
import com.wanglei.domain.ResponseResult;
import com.wanglei.domain.entity.Menu;
import com.wanglei.domain.entity.User;
import com.wanglei.domain.vo.InfoVo;
import com.wanglei.domain.vo.RoutersVo;
import com.wanglei.domain.vo.UserInfoVo;
import com.wanglei.enums.AppHttpCodeEnum;
import com.wanglei.exception.SystemException;
import com.wanglei.service.LoginService;
import com.wanglei.service.MenuService;
import com.wanglei.service.RoleService;
import com.wanglei.utils.BeanCopyUtils;
import com.wanglei.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class AdminLoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;

    @PostMapping("/user/login")
    public ResponseResult login(@RequestBody User user){
        if (!StringUtils.hasText(user.getUserName())){
            //提示 必须要传用户名
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        System.out.println("111");
        return loginService.login(user);
    }

    @GetMapping("/getInfo")
    public ResponseResult getInfo() {
        //获取userInfo
        User user = SecurityUtils.getLoginUser().getUser();
        Long id = user.getId();
        //获取permissions
        List<String> permissions = menuService.selectPermsByUserId(id);
        //获取roles
        List<String> roles = roleService.selectRolesByUserId(id);
        //vo
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        InfoVo infoVo = new InfoVo(permissions,roles,userInfoVo);
        return ResponseResult.okResult(infoVo);
    }

    @GetMapping("/getRouters")
    public ResponseResult getRouters(){
        //获取userid
        Long userId = SecurityUtils.getLoginUser().getUser().getId();
        List<Menu> menus = menuService.selectRouterMenuTreeByUserId(userId);
        return ResponseResult.okResult(new RoutersVo(menus));
    }

    @PostMapping("/user/logout")
    public ResponseResult logout(){
        return loginService.logout();
    }

}
